package com.medvalley.tcm.controller;

import com.medvalley.tcm.base.BusinessException;
import com.medvalley.tcm.base.Constants;
import com.medvalley.tcm.base.Result;
import com.medvalley.tcm.cache.RedisCache;
import com.medvalley.tcm.domain.UserInfo;
import com.medvalley.tcm.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by LinSong on 2018/3/7.
 */
public abstract class BaseController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserInfoService userInfoService;

    protected Result success() {
        return new Result(Constants.HTTP_SUCCESS_CODE, Constants.HTTP_SUCCESS_MESSAGE);
    }

    protected Result success(String message) {
        return new Result(Constants.HTTP_SUCCESS_CODE, message);
    }

    protected Result success(Object data) {
        if (data == null) {
            return success();
        }
        return new Result(Constants.HTTP_SUCCESS_CODE, Constants.HTTP_SUCCESS_MESSAGE, data);
    }

    protected Result success(String message, Object data) {
        return new Result(Constants.HTTP_SUCCESS_CODE, message, data);
    }

    protected Result error(String message) {
        return new Result(Constants.HTTP_ERROR_CODE, message);
    }

    protected Result error(String message, Object data) {
        return new Result(Constants.HTTP_ERROR_CODE, message, data);
    }

    protected String getSessionPhone(HttpServletRequest request) {
        String sessionId = request.getParameter("token");
        String userPhone = redisCache.getValue(Constants.SESSION_PREFIX + sessionId);
        if (StringUtils.isEmpty(userPhone)) {
            throw new BusinessException("请先登录");
        }
        return userPhone;
    }

    protected long getUserId(HttpServletRequest request){
        String phone = this.getSessionPhone(request);
        UserInfo userInfo = userInfoService.getUserInfoByPhone(phone);
        if (userInfo == null) {
            throw new BusinessException("无此用户");
        }
        return userInfo.getId();
    }

    protected String getToken(HttpServletRequest request) {
        String token = request.getParameter("token");
        return token;
    }

}
